package cn.xw.mq.producer;

import cn.xw.config.RabbitMQConfig;
import cn.xw.entity.MessageSendDTO;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author AnHui OuYang
 * @version 1.0
 * created at 2023-04-16 15:01
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TestProducer {

    private final RabbitTemplate rabbitTemplate;

    /***
     * 生产者方法
     */
    public void producerSendMsg() {
        //消息任务准备
        HashMap<String, String> sendMsg = new HashMap<>();
        sendMsg.put("quick.orange.rabbit", "被队列 Q1 Q2 接收到");
        sendMsg.put("lazy.orange.elephant", "被队列 Q1 Q2 接收到");
        sendMsg.put("quick.orange.fox", "被队列 Q1 接收到");
        sendMsg.put("lazy.brown.fox", "被队列 Q2 接收到");
        sendMsg.put("lazy.pink.rabbit", "虽然满足两个绑定规则但两个规则都是在Q2队列，所有只要Q2接收一次");
        sendMsg.put("quick.brown.fox", "不匹配任何绑定不会被任何队列接收到会被丢弃");
        sendMsg.put("quick.orange.male.rabbit", "是四个单词不匹配任何绑定会被丢弃");
        sendMsg.put("lazy.orange.male.rabbit", "是四个单词但匹配 Q2");
        //循环发送消息任务
        for (Map.Entry<String, String> msg : sendMsg.entrySet()) {
            String routKey = msg.getKey();  //主题路由key
            String message = msg.getValue();//消息任务
            //创建对象
            MessageSendDTO build = MessageSendDTO.builder().msgBody("基本信息：" + message + " 路由信息：" + routKey).build();
            //消息转换为JSON格式并转为字节数组
            byte[] bytes = JSONObject.toJSONString(build).getBytes(StandardCharsets.UTF_8);
            //发送消息
            rabbitTemplate.convertAndSend(RabbitMQConfig.TOPIC_EXCHANGE, routKey, bytes);
        }
        log.info("生产者发送信息完成，已经交由给交换机.....");
    }
}
